#!/usr/bin/env node

const API_BASE = 'http://localhost:3002/api/v1';

async function makeRequest(url, options = {}) {
  try {
    const response = await fetch(url, {
      headers: {
        'Content-Type': 'application/json',
        ...options.headers
      },
      ...options
    });
    
    const data = await response.json();
    console.log(`${options.method || 'GET'} ${url}`);
    console.log(`Status: ${response.status}`);
    console.log('Response:', JSON.stringify(data, null, 2));
    console.log('---');
    
    return { response, data };
  } catch (error) {
    console.error('Request failed:', error.message);
    return null;
  }
}

async function testApiKeys() {
  console.log('🧪 Testing API Key Management\n');

  // 1. 登录获取JWT token
  console.log('1. Login to get JWT token');
  const loginResult = await makeRequest(`${API_BASE}/auth/login`, {
    method: 'POST',
    body: JSON.stringify({
      email: 'testdev@example.com',
      password: 'password123'
    })
  });

  if (!loginResult || !loginResult.data.success) {
    console.error('❌ Login failed');
    return;
  }

  const token = loginResult.data.data.tokens.accessToken;
  console.log('✅ Login successful, got JWT token\n');

  // 2. 创建API密钥
  console.log('2. Create API key');
  const createResult = await makeRequest(`${API_BASE}/keys`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({
      name: 'Test API Key',
      permissions: ['plugin:read', 'plugin:write'],
      rateLimitPerHour: 1000
    })
  });

  if (!createResult || !createResult.data.success) {
    console.error('❌ API key creation failed');
    return;
  }

  const apiKey = createResult.data.data.secretKey;
  const keyId = createResult.data.data.apiKey.id;
  console.log('✅ API key created successfully');
  console.log(`🔑 API Key: ${apiKey}\n`);

  // 3. 获取API密钥列表
  console.log('3. Get API keys list');
  await makeRequest(`${API_BASE}/keys`, {
    headers: {
      'Authorization': `Bearer ${token}`
    }
  });

  // 4. 使用API密钥访问受保护的端点
  console.log('4. Test API key authentication');
  await makeRequest(`${API_BASE}/developer/plugins`, {
    headers: {
      'X-API-Key': apiKey
    }
  });

  // 4.1 测试API密钥访问插件列表
  console.log('4.1. Test API key with public plugins endpoint');
  await makeRequest(`${API_BASE}/plugins`, {
    headers: {
      'X-API-Key': apiKey
    }
  });

  // 5. 更新API密钥
  console.log('5. Update API key');
  await makeRequest(`${API_BASE}/keys/${keyId}`, {
    method: 'PUT',
    headers: {
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({
      name: 'Updated Test API Key',
      rateLimitPerHour: 2000
    })
  });

  // 6. 删除API密钥
  console.log('6. Delete API key');
  await makeRequest(`${API_BASE}/keys/${keyId}`, {
    method: 'DELETE',
    headers: {
      'Authorization': `Bearer ${token}`
    }
  });

  console.log('🎉 API key testing completed!');
}

// 运行测试
testApiKeys().catch(console.error);
